//
//  HYShowQRCodeView.m
//  XPlayer
//
//  Created by 张水 on 2023/9/22.
//

#import "HYShowQRCodeView.h"
#import <Photos/Photos.h>
#import <HYUIKit/HYAlertShowAnimate.h>
#import <HYUIKit/UIView+effectView.h>

@interface HYShowQRCodeView()

@property (nonatomic, assign) BOOL isFull;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UILabel *fileNameLabel;

@property (nonatomic, strong) UIButton *copyButton;

@property (nonatomic, strong) UIImageView *qrImageView;

@property (nonatomic, strong) UILabel *linkLabel;

@property (nonatomic, strong) UIButton *saveImageButton;

@property (nonatomic, copy) NSString *linkString;

@property (nonatomic, copy) dispatch_block_t disappear;

@end

@implementation HYShowQRCodeView

- (instancetype)initWithFileName:(NSString *)fileName
                         linkUrl:(NSString *)linkUrl
                          isFull:(BOOL)isFull
                       disappear:(dispatch_block_t)disappear
{
    if (self = [super init]) {
        self.linkString = linkUrl;
        self.fileNameLabel.text = fileName;
        self.disappear = disappear;
        self.linkLabel.text = [NSString stringWithFormat:@"  %@",linkUrl];
        self.isFull = isFull;
        [self configUI];
    }
    return self;
}

- (void)configUI
{
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    [self.contentView addFrostingEffect];
    
    [self.contentView addSubview:self.linkLabel];
    [self.linkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@250);
        make.top.equalTo(self.contentView).offset(30);
        make.centerX.equalTo(self.contentView.mas_centerX);
        make.height.equalTo(@40);
    }];
    
    [self.contentView addSubview:self.copyButton];
    [self.copyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@60);
        make.centerY.equalTo(self.linkLabel.mas_centerY);
        make.leading.equalTo(self.linkLabel.mas_trailing).offset(10);
    }];
    
    [self.contentView addSubview:self.qrImageView];
    [self.qrImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contentView);
        make.top.equalTo(self.linkLabel.mas_bottom).offset(20);
        make.width.height.mas_equalTo(self.isFull?200:250);
    }];
    
    [self creatQRCodeImage];
    
    [self.contentView addSubview:self.fileNameLabel];
    [self.fileNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.qrImageView.mas_bottom);
        make.leading.equalTo(self.qrImageView.mas_leading);
        make.trailing.equalTo(self.qrImageView.mas_trailing);
        make.height.equalTo(@40);
    }];
    
    [self.contentView addSubview:self.saveImageButton];
    [self.saveImageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.fileNameLabel.mas_bottom).offset(self.isFull?10:20);
        make.centerX.equalTo(self.contentView.mas_centerX);
        make.width.equalTo(@120);
        make.height.equalTo(@30);
    }];
}

-(void)creatQRCodeImage
{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSData *data = [[self fetchCurrentVideoInfo] dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];
    CIImage *outPutImage = [filter outputImage];
    self.qrImageView.image = [self createNonInterpolatedUIImageFormCIImage:outPutImage withSize:250];
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

- (NSString *)fetchCurrentVideoInfo
{
    return [NSString stringWithFormat:@"%@+%@",self.fileNameLabel.text,self.linkString];
}

- (void)showInView:(UIView *)superView
{
    self.frame = CGRectMake(0, 0, self.isFull?kScreenHeight:kScreenWidth, self.isFull?kScreenHeight:500);
    [HYAlertShowAnimate showInView:superView
                         alertView:self
                         popupMode:self.isFull?View_Popup_Mode_Right:View_Popup_Mode_Down
                           bgAlpha:0.3
                  outsideDisappear:YES
                         disappear:self.disappear];
}

- (void)copyButtonAction:(UIButton *)sedner
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.linkString;
    [HYHub showMessage:NSLocalizedString(@"链接已复制", nil)];
}

- (void)saveImageButtonAction:(UIButton *)sender
{
    [self saveImageToPhoto];
}

- (void)saveImageToPhoto
{
    NSData *imageData;
    if(UIImagePNGRepresentation(self.qrImageView.image)){
        imageData = UIImagePNGRepresentation(self.qrImageView.image);
    }else{
        imageData = UIImageJPEGRepresentation(self.qrImageView.image,1.0);
    }
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:imageData options:nil];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(error){
                [HYHub showMessage:NSLocalizedString(@"保存失败", nil)];
            }else
            {
                [HYHub showMessage:NSLocalizedString(@"保存成功", nil)];
            }
        });
    }];
}

#pragma mark - loayLoad
- (UIView *)contentView
{
    if (_contentView == nil) {
        _contentView = [[UIView alloc]init];
        _contentView.layer.cornerRadius = 25.f;
        _contentView.layer.masksToBounds = YES;
    }
    return _contentView;
}

- (UILabel *)fileNameLabel
{
    if(_fileNameLabel == nil){
        _fileNameLabel = [[UILabel alloc]init];
        _fileNameLabel.font = FONT_SIZE(18);
        _fileNameLabel.textColor = UIColor.whiteColor;
        _fileNameLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _fileNameLabel;
}

- (UILabel *)linkLabel
{
    if(_linkLabel == nil){
        _linkLabel = [[UILabel alloc]init];
        _linkLabel.font = FONT_SIZE(16);
        _linkLabel.textColor = [UIColor blackColor];
        _linkLabel.backgroundColor = [CommUtls colorWithHexString:@"#FFFFFF" Alpha:0.4];
        _linkLabel.layer.cornerRadius = 20.f;
        _linkLabel.layer.masksToBounds = YES;
    }
    return _linkLabel;
}

- (UIImageView *)qrImageView
{
    if (_qrImageView == nil) {
        _qrImageView = [[UIImageView alloc]init];
        _saveImageButton.layer.cornerRadius = 4.f;
    }
    return _qrImageView;
}
- (UIButton *)copyButton
{
    if (_copyButton == nil) {
        _copyButton = [[UIButton alloc]init];
        [_copyButton setImage:[UIImage imageNamed:@"icon_copy"] forState:UIControlStateNormal];
        [_copyButton addTarget:self action:@selector(copyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _copyButton;
}

- (UIButton *)saveImageButton
{
    if (_saveImageButton == nil) {
        _saveImageButton = [[UIButton alloc]init];
        [_saveImageButton setTitle:NSLocalizedString(@"保存至相册", nil) forState:UIControlStateNormal];
        [_saveImageButton setBackgroundColor:[CommUtls colorWithHexString:@"#FFFFFF" Alpha:0.4]];
        _saveImageButton.layer.cornerRadius = 15.f;
        [_saveImageButton addTarget:self action:@selector(saveImageButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveImageButton;
}

@end
